package geektime.im.lecture.redis;

import io.netty.util.internal.PlatformDependent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import redis.embedded.RedisServer;
import redis.embedded.RedisServerBuilder;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

@Component
@Profile("dev")
@Slf4j
public class EmbededRedis {

    @Value("${spring.redis.port}")
    private int redisPort;

    private RedisServer redisServer;

    @PostConstruct
    public void startRedis() throws IOException {
        if (PlatformDependent.isWindows()){
            RedisServerBuilder redisServerBuilder = RedisServer.builder().port(redisPort).setting("maxheap 200m");
            redisServer = redisServerBuilder.build();
        }else if(PlatformDependent.isOsx()){
            redisServer = new RedisServer(redisPort);
        }else {
            redisServer = new RedisServer(redisPort);
        }
        redisServer.start();
        log.info("redis start port in {}",redisPort);
    }

    @PreDestroy
    public void stopRedis() {
        redisServer.stop();
    }
}
